package com.yxc.spring_cache.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yxc.spring_cache.entity.Book;
import com.yxc.spring_cache.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
@CacheConfig(cacheNames = "book",keyGenerator = "bookSearchGenerator")
public class BookController {

    @Autowired
    BookService bookService;
    @Resource
    CacheManager cacheManager;

    @GetMapping
    @Cacheable(key = "#root.targetClass+'userList'")
    public List<Book> getlist() {
        return bookService.list();
    }

    @GetMapping("/{id}")
    @Cacheable(condition = "#id%2==0")
    public Book getBookById(@PathVariable Integer id) {
        return bookService.getById(id);
    }

    @CacheEvict(allEntries = true) //根据参数指定的键来删除缓存
    @DeleteMapping("/{id}")
    public String deleteBook(@PathVariable Integer id){ //根据id号删除一本书, 同时删除缓存
        System.out.println("从数据库删除一本书，同时删除key为"+id+"的缓存");
//        bookService.removeById(id);
        return "删除成功";
    }

    @PutMapping
    @Caching(
            put=@CachePut,
            evict = @CacheEvict(key = "#root.targetClass+'userList'")
    )
//    @CachePut(value="book",key="#book.id")//修改缓存
    public Book updateBook(@RequestBody Book book){ //修改一本书
        System.out.println("从数据库修改一本书，同时修改缓存，key为"+book.getId());
        bookService.saveOrUpdate(book);
        return book;
    }

//    @Cacheable(key="(#condition.bookName!=null?#condition.bookName:'')+(#condition.category!=null?#condition.category:'')+(#condition.author!=null?#condition.author:'')")  //定义缓存的键为拼接的参数,值是方法的返回值
    @PostMapping
    @Cacheable()
    public List<Book> searchBooks(@RequestBody Book condition){ //查找一本书
        System.out.println("条件查询,并添加到缓存，key为搜索条件的组合");
        System.out.println("condition:"+condition);

        LambdaQueryWrapper<Book> queryWrapper= new LambdaQueryWrapper<>();
        if (StringUtils.hasText(condition.getName())) {
            queryWrapper.like(Book::getName,condition.getName());
        }
        if (StringUtils.hasText(condition.getCategory())) {
            queryWrapper.like(Book::getCategory,condition.getCategory());
        }
        if (StringUtils.hasText(condition.getAuthor())) {
            queryWrapper.like(Book::getAuthor,condition.getAuthor());
        }

        return bookService.list(queryWrapper);
    }

}
